/*
 * @Description: 画图
 * @Author: kanglin
 * @Date: 2018-09-03 10:05:33
 * @Copyright: Created by Panxsoft.
 */

export default class Chart {
	/**
	 * @param {number} width 画布宽
	 * @param {number} height 画布高
	 * @param {number} color  背景颜色
	 */
	constructor(width, height, color = 'rgba(255, 255, 255, 0)') {
		this.elements = []; // 要渲染的元素队列
		this.canvas = document.createElement('canvas');
		this.context = this.canvas.getContext('2d');
		this.canvas.width = width;
		this.canvas.height = height;
		this.color = color;
		this.resetCanvasBackground();
	}

	resetCanvasBackground() {
		// this.context.fillStyle = this.color;
		this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
	}

	/**
	 *  预加载资源
	 */
	static preloadResources(resource) {
		return new Promise((resolve, reject) => {
			let count = 0;
			const result = {};
			const resource_keys = Object.keys(resource);
			resource_keys.forEach((key) => {
				const image = new Image();
				image.src = resource[key];
				result[key] = image;
				image.onload = function onload() {
					count += 1;
					if (count === resource_keys.length) {
						resolve(result);
					}
				};
				image.onerror = function error() {
					reject(new Error('图片加载错误'));
				};
			});
		});
	}

	/**
	 *  添加元素
	 */
	add(el) {
		this.elements.push(el);
		return this; // 链式调用
	}

	/**
	 *  渲染列表中的元素
	 */
	render() {
		this.resetCanvasBackground();
		this.elements.forEach((item) => {
			item.draw.call(item, this.context);
		});
		return this.getDataURL();
	}

	/**
	 * 获取图片
	 */
	getDataURL(format = 'image/png') {
		return this.canvas.toDataURL(format);
	}
}
